<template>
  <div>
    <el-drawer
      v-if="visible"
      title="客户信息"
      class="csmDetail"
      :visible.sync="visible"
      :with-header="false"
      direction="rtl"
      :wrapper-closable="true"
      :append-to-body="true"
    >
      <div class="item">
        <div class="title">
          <div class="title-text">{{ csmInfo.csmName }}({{ csmInfo.csmCode }})</div>
          <el-tag class="tag">{{ formatColumnMap(statusMap.customerType, "value", csmInfo.csmType, "desc") }}</el-tag>
          <div :class="csmInfo.warnLevel === 0? 'circle green' : 'circle red'">{{ formatColumnMap(warnLevelMap, "value", csmInfo.warnLevel, "desc") }}</div>
        </div>
        <el-tabs
          v-model="activeName"
          style="min-height: 200px;"
          @tab-click="tabsClick"
        >
          <el-tab-pane lazy label="基本信息" name="user">
            <tab-user :csm-info="csmInfo" :group-type-map="groupTypeMap" :label-map="labelMap" @changeTab="changeTab" />
          </el-tab-pane>
          <el-tab-pane lazy label="租瓶信息" name="bottle">
            <tab-bottle ref="bottle" :csm-id="csmInfo.csmId" />
          </el-tab-pane>
          <!-- <el-tab-pane lazy label="保险信息" name="insurance">
            <tab-insurance ref="insurance" :csm-id="csmInfo.csmId" />
          </el-tab-pane> -->
          <!-- <el-tab-pane lazy label="证件信息" name="certificate">
            <tab-certificate ref="certificate" :csm-id="csmInfo.csmId" />
          </el-tab-pane> -->
          <el-tab-pane lazy label="订单信息" name="history">
            <tab-history ref="history" :csm-id="csmInfo.csmId" />
          </el-tab-pane>
          <el-tab-pane lazy label="安检记录" name="check">
            <tab-check ref="check" :csm-id="csmInfo.csmId" :tree-data="treeData" />
          </el-tab-pane>
          <el-tab-pane lazy label="充值记录" name="recharge">
            <tab-recharge ref="recharge" :csm-info="csmInfo" />
          </el-tab-pane>
          <el-tab-pane lazy label="月结账单" name="month">
            <tab-month ref="month" :csm-code="csmInfo.csmCode" />
          </el-tab-pane>
          <el-tab-pane lazy label="积分记录" name="score">
            <tab-score ref="score" :csm-id="csmInfo.csmId" />
          </el-tab-pane>
          <el-tab-pane lazy label="变更历史" name="change">
            <tab-change ref="change" :csm-id="csmInfo.csmId" />
          </el-tab-pane>
          <el-tab-pane lazy label="特价记录" name="price">
            <tab-special ref="price" :csm-id="csmInfo.csmId" />
          </el-tab-pane>
          <el-tab-pane lazy label="附件" name="file">
            <tab-accessory
              ref="file"
              :card-type="statusMap.cardType"
              :csm-code="csmInfo.csmCode"
            />
          </el-tab-pane>
          <el-tab-pane lazy label="客户组" name="csmGroup">
            <tab-csmGroup ref="csmGroup" :csm-info="csmInfo" :customer-type-map="customerTypeMap" :csm-status-map="csmStatusMap" :group-type-map="groupTypeMap" :sub-type-all-list="subTypeAllList" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="bottom">
        <div class="btn-group">
          <div class="btns">
            <el-button v-if="csmInfo.csmStatus !== -1 && csmInfo.csmStatus !== 2 && csmInfo.csmStatus !== 4" v-show="$btnPermission([20101, 7])" type="primary" @click="update('audit')">审核</el-button>
            <el-button v-if="csmInfo.csmStatus !== -1" v-show="$btnPermission([20101, 6])" type="primary" @click="update('edit')">编辑</el-button>
            <el-button v-if="csmInfo.csmStatus !== -1" v-show="$btnPermission([20101, 8])" type="primary" @click="insurance">投保</el-button>
            <el-button v-if="csmInfo.csmStatus !== -1" v-show="$btnPermission([20101, 9])" type="primary" @click="normalReceiptsAdd">押金登记</el-button>
            <el-button v-if="csmInfo.csmStatus !== -1" v-show="$btnPermission([20101, 10])" type="warning" @click="updateCode">编号变更</el-button>
            <el-button v-if="csmInfo.csmStatus !== 1 && csmInfo.csmStatus !== -1" v-show="$btnPermission([20101 ,11])" type="primary" @click="del">销户</el-button>
            <el-button v-if="csmInfo.csmStatus === 2" v-show="$btnPermission([20101, 12])" type="danger" @click="updateCsmStatus">拉黑</el-button>
            <el-button v-if="csmInfo.csmStatus === 4" v-show="$btnPermission([20101, 13])" type="primary" @click="updateCsmStatus">移除拉黑</el-button>
            <el-button v-if="csmInfo.groupCode" v-show="$btnPermission([20101, 15])" type="danger" @click="removeGroup">移除组</el-button>
          </div>
          <el-button @click="visible = false">关闭</el-button>
        </div>
      </div>
      <editCsm ref="editCsm" :parent-fetch-data="parentFetchData" :tree-data="treeData" :group-type-map="groupTypeMap" />
      <insure ref="insure" />
      <normalReceiptsAdd ref="normalReceiptsAdd" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" />
      <update-code ref="updateCode" :parent-fetch-data="parentFetchData" />
      <xiaohu ref="xiaohu" :xiao-hu-fn="xiaoHuFn" />
      <blacklistCsm ref="blacklistCsm" />
    </el-drawer>
  </div>
</template>

<script>
  import { queryMap, queryCsmIdInfo, queryAddCsmDefaultData, customerCancle, updateCsmStatus, customerInvocie, customerInfo, queryRiskTrackMap, cancelCsmGroup, getCustomerLabel } from '@/api'
  import { parseTime, formatColumnMap } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import TabUser from './TabUser'
  import TabBottle from './TabBottle'
  // import TabInsurance from './TabInsurance'
  // import TabCertificate from './TabCertificate'
  import TabHistory from './TabHistory'
  import TabScore from './TabScore'
  import TabChange from './TabChange'
  import TabRecharge from './TabRecharge'
  import TabSpecial from './TabSpecial'
  import TabAccessory from './TabAccessory'
  import TabCheck from './TabCheck.vue'
  import TabMonth from './TabMonth.vue'
  import TabCsmGroup from './TabCsmGroup.vue'
  import UpdateCode from '../../customerCenter/customerManage/components/UpdateCode.vue'
  import xiaohu from '../../customerCenter/customerManage/components/xiaohu.vue'
  import EditCsm from '../../customerCenter/customerManage/components/EditCsm'
  import Insure from '../../customerCenter/customerManage/components/Insure'
  import NormalReceiptsAdd from '@/views/components/NormalReceiptsAdd'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import blacklistCsm from '../../customerCenter/customerManage/components/blacklistCsm'
  import store from '@/store'

  export default {
    name: 'csm-detail',
    components: {
      TabUser,
      TabBottle,
      // TabInsurance,
      // TabCertificate,
      TabHistory,
      TabScore,
      TabChange,
      TabRecharge,
      TabSpecial,
      TabAccessory,
      UpdateCode,
      xiaohu,
      EditCsm,
      Insure,
      NormalReceiptsAdd,
      TabCheck,
      TabMonth,
      TabCsmGroup,
      blacklistCsm
    },
    props: {
      // type 2 是客户等级管理 历史详情
      type: {
        type: Number,
        default: 1
      },
      parentFetchData: {
        type: Function
      }
    },
    data() {
      return {
        parseTime,
        visible: false,
        activeName: 'user',
        csmId: '',
        csmInfo: {},
        warnLevelMap: [],
        groupTypeMap: [],
        statusMap: {}, // 状态枚举
        customerTypeMap: [], // 客户类型枚举
        csmStatusMap: [], // 客户状态枚举
        calcTypeList: [],
        paymenFilList: [],
        treeData: [],
        showOperate: false,
        subTypeAllList: [
          {
            label: '餐饮',
            value: 1
          },
          {
            label: '餐饮(个人)',
            value: 2
          },
          {
            label: '工厂',
            value: 3
          },
          {
            label: '机关事业单位',
            value: 4
          },
          {
            label: '部队',
            value: 5
          },
          {
            label: '居民(个人)',
            value: 6
          },
          {
            label: '学校',
            value: 7
          },
          {
            label: '其他商业',
            value: 8
          },
          {
            label: '餐饮(连锁)',
            value: 9
          },
          {
            label: '住宿业',
            value: 10
          },
          {
            label: '商贸服务业',
            value: 11
          },
          {
            label: '医疗卫生',
            value: 12
          },
          {
            label: '社会保障',
            value: 13
          }
        ],
        labelMap: []
      }
    },
    computed: {
      ...mapGetters([
        'menusArr', 'orgList'
      ])
    },
    async created() {
      await Promise.all([this.getTreeData(), this.queryOptionsMap(), this.getStatusMap(), this.getdanger(), this.getCustomerLabelData()])
    },
    mounted() {
      this.$watch('activeName', (val) => {
        if (val !== 'user') {
          console.log(val)
          this.$nextTick(() => {
            this.$refs[val].getData({})
          })
        }
      })
    },
    methods: {
      formatColumnMap,
      async open(temp) {
        return new Promise(async(resolve) => {
          if (temp) {
            this.resolve = resolve
            this.activeName = 'user'
            this.csmId = temp.csmId
            await this.getData(temp.csmId)
          }
        })
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7, res8] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerFromPlat' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerNewType' }),
          mergeAsyncFunc(queryMap, { enumName: 'AccCsmcardCardStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'CsmGroupType' })])
        this.customerTypeMap = res1.data // 客户类型
        this.newFromMap = res2.data // 客户来源
        this.csmStatusMap = res3.data // 客户状态
        this.csmNewTypeMap = res4.data // 开户类型
        this.accCsmcardCardStatusMap = res5.data // 充值卡状态
        this.calcTypeList = res6.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res7.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.groupTypeMap = res8.data // 客户组类型
      },
      async getData(csmId) {
        const res = await queryCsmIdInfo({
          csmId: csmId
        })
        if (res.data) {
          this.csmInfo = res.data
          this.visible = true
        } else {
          this.$message.error('该用户不存在')
        }
      },
      async getStatusMap() {
        const res = await queryAddCsmDefaultData()
        // this.statusMap = res.data.map(l => JSON.parse(l))
        var obj = {}
        for (var value in res.data) {
          // console.log(item)
          if (this.isJsonString(res.data[value])) {
            var item = JSON.parse(res.data[value])
            obj[value] = item
          }
        }
        this.statusMap = obj
      },
      // 查询隐患等级
      async getdanger() {
        const res = await queryRiskTrackMap()
        const data = JSON.parse(res.data.warnLevel) // 隐患等级
        if (data) {
          this.warnLevelMap = []
          data.forEach(item => {
            this.warnLevelMap.push({
              value: item.keyVal,
              desc: item.keyName
            })
          })
        }
      },
      // 判断是否为JSON对象
      isJsonString(str) {
        try {
          if (typeof JSON.parse(str) === 'object') {
            return true
          }
        } catch (e) {
          console.log()
        }
        return false
      },
      tabsClick(val) {
      // console.log(this.activeName)
      // val.getData()
      },
      reset() {
        this.csmInfo = {}
        this.activeName = 'user'
      },
      // 编辑
      async update(type) {
        const code = {
          csmCode: this.csmInfo.csmCode
        }
        const res = await customerInfo(code)
        const csmId01 = {
          csmId: this.csmInfo.csmId,
          taxType: 1
        }
        const csmId02 = {
          csmId: this.csmInfo.csmId,
          taxType: 2
        }
        var list = [res.data.provinceCode, res.data.cityCode, res.data.countryCode, res.data.streetCode].filter(l => l * 1 !== 0 && l !== undefined)

        res.data.AddressData = [...list]
        const res01 = await customerInvocie(csmId01)
        const res02 = await customerInvocie(csmId02)
        await this.$refs.editCsm.open(res, res01, res02, type)
        this.getData(this.csmId)
      },
      // 投保
      async insurance() {
        await this.$refs.insure.open(this.csmInfo)
      },
      // 押金登记
      async normalReceiptsAdd() {
        const res = await customerInfo({ csmCode: this.csmInfo.csmCode })
        await this.$refs.normalReceiptsAdd.open(res.data, 'add', 'toubao', this.csmInfo)
      },
      // 编号变更
      async updateCode() {
        await this.$refs.updateCode.open(this.csmInfo)
      },
      del() {
        const code = {
          csmId: this.csmInfo.csmId
        }
        this.$refs.xiaohu.open(code, this.csmInfo)
      },
      async xiaoHuFn(params) {
        const res = await customerCancle(params)
        if (!res.data) {
          this.$message.success('销户成功')
          this.$refs.lbTable.fetch({ currentPage: 1 })
        } else {
          this.$message({
            dangerouslyUseHTMLString: true,
            type: 'warning',
            message: res.data
          })
        }
      },
      async updateCsmStatus() {
        if (this.csmInfo.csmStatus === 2) {
          // this.$confirm(`确定将该用户拉黑？`, '提示', {
          //   type: 'warning'
          // }).then(() => {
          //   const params = {
          //     csmId: this.csmInfo.csmId,
          //     csmStatus: 4
          //   }
          //   updateCsmStatus(params).then(res => {
          //     if (res.data) {
          //       this.$message.success('操作成功')
          //       this.getData(this.csmInfo.csmId)
          //     }
          //   })
          // })
          await this.$refs.blacklistCsm.open(this.csmInfo)
          this.getData(this.csmId)
        } else {
          const params = {
            csmId: this.csmInfo.csmId,
            csmStatus: 2
          }
          updateCsmStatus(params).then(res => {
            if (res.data) {
              this.$message.success('操作成功')
              this.getData(this.csmInfo.csmId)
            }
          })
        }
      },
      // 移除组
      removeGroup() {
        this.$confirm(`您确认移除组吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          const params = {
            csmId: this.csmInfo.csmId
          }
          cancelCsmGroup(params).then(res => {
            if (res.data) {
              this.$message.success('操作成功')
              this.getData(this.csmInfo.csmId)
            }
          })
        })
      },
      changeTab(name) {
        console.log(name)
        this.activeName = name
      },
      // 活跃度
      async getCustomerLabelData() {
        const res = await getCustomerLabel()
        if (res && res.data) {
          this.labelMap = res.data
        }
      },
      // 获取权限
      getBtnPermission(scope) {
        // 超级管理员返回所有用户权限
        if (store.getters.userInfo && ((store.getters.userInfo.utype & 0x01) === 0x01)) return true
        const menusArr = store.getters && store.getters.menusArr
        const btnPer = menusArr.find(role => role.menuId === scope[0])
        const btnScopes = [btnPer.btnScope]
        return btnScopes.some(btnScope => btnScope >> (scope[1] - 1) & 0x01)
      }
    }
  }
</script>

<style lang="scss" scoped>
.csmDetail {
  /deep/.el-drawer {
    width: 75% !important;
  }
}
.item {
  height: calc(100vh - 55px);
  padding: 20px;
  overflow-y: auto;
  .title {
    display: flex;
    margin-bottom: 20px;
    .title-text {
      line-height: 25px;
    }
    .tag {
      margin: 0 10px;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }
  .content {
    margin-bottom: 30px;
  }
}
.bottom {
  position: fixed;
  bottom: 0;
  z-index: 99;
  width: 75%;
  height: 55px;
  background: white;
  border: 2px solid #DCDFE6;
  .btn-group {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    margin-right: 10px;
    .btns {
      display: flex;
      margin-left: 15px;
    }
  }
}
.circle {
  position: absolute;
  top: 50px;
  right: 50px;
  z-index: 99;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 110px;
  height: 110px;
  padding: 10px;
  margin-top: -30px;
  font-size: 16px;
  font-weight: 600;
  text-align: center;
  border-radius: 50%;
  transform: rotateZ(-25deg);
}
.red {
  color: #E76E7E;
  border: 8px solid #E76E7E;
}
.green {
  color: #1ABC9C;
  border: 8px solid #1ABC9C;
}
</style>
